package a05_双指针法;

/**
 * <p>
 * a08_环形链表2
 * </p>
 *
 * @author flyduck
 * @since 2024-07-23
 */
public class a08_环形链表2 {

    public static void main(String[] args) {
        ListNode head = new ListNode(3);
        ListNode a = new ListNode(2);
        a.next = new ListNode(0);
        a.next.next = new ListNode(-4);
        a.next.next.next = a;
        head.next = a;
        ListNode listNode = detectCycle(head);
        System.out.println();

    }

    public static ListNode detectCycle(ListNode head) {
        ListNode slowNode = head;
        ListNode fastNode = head;

        while (fastNode != null && fastNode.next != null) {
            slowNode = slowNode.next;
            fastNode = fastNode.next.next;

            if(slowNode == fastNode){
                ListNode node1 = head;
                ListNode node2 = slowNode;
                while (node1 != node2) {
                    node1 = node1.next;
                    node2 = node2.next;
                }
                return node1;
            }
        }
        return null;
    }
}
